package com.sjn.auth.jwt.controller;

import com.sjn.common.response.ResponseResult;
import com.sjn.common_auth.jwt.request.LoginRequest;
import com.sjn.common_auth.jwt.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: sjn
 * @Data: 2025/6/16 16:42
 */
@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证接口")
public class AuthController {

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public ResponseResult<Map<String, String>> login(@RequestBody LoginRequest request) {
        // 1. 验证用户名密码 (伪代码)
//        if (!authenticate(request.getUsername(), request.getPassword())) {
//            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
//        }

        // 2. 创建JWT
        Map<String, Object> claims = new HashMap<>();
        claims.put("role", "user"); // 添加自定义声明

        String token = JwtUtil.generateToken(request.getUsername(), claims);

        // 3. 返回响应
        Map<String, String> response = new HashMap<>();
        response.put("token", token);
        return new ResponseResult<>().success(response);
    }

    /**
     * 测试受保护的端点
     *
     * @param authHeader
     * @return
     */
    @GetMapping("/protected")
    @Operation(summary = "权限认证")
    public ResponseResult<Map<String, String>> protectedEndpoint(
            @RequestHeader("Authorization") String authHeader) {
        Map<String, String> response = new HashMap<>();
        // 验证Authorization头
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return new ResponseResult<>().failure("token 无效");
        }

        String token = authHeader.substring(7);
        if (!JwtUtil.validateToken(token)) {
            return new ResponseResult<>().failure("认证失败");
        }

        // 获取用户信息
        String username = JwtUtil.getUsernameFromToken(token);

        response.put("token", "欢迎, " + username + "! 这是受保护的内容");
        return new ResponseResult<>().success(response);
    }
}
